package br.ufpe.cin.rdfilter.util;

import java.net.URL;
import java.util.ArrayList;

public class URLHandler {

	/**
	 * 
	 * @param url
	 * @return prefix of the given URL. Let's prefix the initial part of the URL
	 *         that comes before the name of the file.
	 */
	public String getPrefixURL(URL url) {

		String prefixURL = null;

		String urlHost = url.getHost();
		String urlPath = url.getPath();

		int barIndex = urlPath.lastIndexOf("/");

		// building the prefix from the host and the initial part of path
		if (barIndex != -1) {

			if (urlPath.substring(barIndex) != null
					&& !urlPath.substring(barIndex).contains(".")) {
				prefixURL = urlHost + urlPath;
			} else {
				prefixURL = urlHost + urlPath.substring(0, barIndex);
			}
		} else {
			prefixURL = urlHost + urlPath;
		}

		// putting the protocol (HTTP) into the prefix
		prefixURL = "http://" + prefixURL;

		return prefixURL;
	}

	/**
	 * 
	 * @param urlList
	 * @param prefixURL
	 * @return the URL from the urlList that has the longest prefix in common
	 *         with the prefixUrl.
	 */
	public String getLongestPrefixCommonURL(ArrayList<String> urlList,
			String prefixURL) {

		String longestPrefixCommonUrl = null;
		int longestPrefixLength = 0, commonCharsCount;
		boolean endLoop;

		for (String url : urlList) {

			commonCharsCount = 0;
			endLoop = false;

			// calculating the size of the common part of url's prefix with the
			// prefixUrl
			for (int i = 0; i < url.length() && !endLoop; i++) {
				if ((prefixURL.length() > i - 1)
						&& (url.charAt(i) == prefixURL.charAt(i))) { // common
																		// char
					commonCharsCount++;
				} else { // miss, halt the loop
					endLoop = true;
				}
			}

			// it found a longer prefix in common with the prefixUrl
			if (commonCharsCount > longestPrefixLength) {
				longestPrefixLength = commonCharsCount;
				longestPrefixCommonUrl = url;
			}

		}

		return longestPrefixCommonUrl;
	}

}
